package routes

import (
	"crypto/md5"
	"fmt"
	"hello-log-seelog/logs"
	"html/template"
	"io"
	"net/http"
	"time"
)

type MyMux struct {
}

func (mx *MyMux) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	logs.Logger.Info("Server...")
	//defer func() { // 异常时处理
	//	if x := recover(); x != nil {
	//		logs.Logger.Info(x)
	//		//systemError(writer, request)
	//	}
	//}()

	if request.URL.Path == "/" {
		index(writer, request)
		return
	}
	if request.URL.Path == "/login" {
		Login(writer, request)
		return
	}
	NotFound(writer, request)
}

func NewMux() *MyMux {
	nmx := MyMux{}
	return &nmx
}

func NotFound(w http.ResponseWriter, r *http.Request) {
	logs.Logger.Error("页面找不到")
	t, _ := template.ParseFiles("gtpls/404.html")
	ErrorInfo := "文件找不到"
	t.Execute(w, ErrorInfo)
}

func SystemError(w http.ResponseWriter, r *http.Request) {
	logs.Logger.Error("系统错误")
	t, _ := template.ParseFiles("gtpls/error.html")
	ErrorInfo := "系统暂时不可用"
	t.Execute(w, ErrorInfo)
}

func index(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	name := r.Form["name"]
	fmt.Fprintf(w, "hello %s", name)
}

func Login(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("gtpls/login.gtpl")
	h := md5.New()
	io.WriteString(h, time.Now().String())
	token := fmt.Sprintf("%x", h.Sum(nil))

	t.Execute(w, token)
}
